package cn.melonlib.aap.user.comp.service;

import cn.melonlib.aap.user.model.entity.Account;
import cn.melonlib.aap.user.model.entity.User;
import cn.melonlib.cores.commons.comp.service.impl.WorkerBasicService;
import cn.melonlib.cores.jpa.model.bean.impl.DefaultQuery;
import cn.melonlib.cores.model.anno.*;
import org.intellij.lang.annotations.Language;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;

@Service
@WorkerComment("用户管理")
@WorkerService(
        module = "user"
        ,model = @WorkerModel(
                modelType = User.class
)
)
public class UserService extends WorkerBasicService<User> {

    @Resource
    private AccountManagerService accountManagerService;

    @WorkerComment("创建用户")
    @WorkerStore
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    public User createUser(
            @WorkerParameter(value = "user",comment = "用户对象",required = true) User user,
            @WorkerParameter(value = "userTypes",comment = "用户身份",required = true) List<String> userTypes,
            @WorkerParameter(value = "tenant",comment = "租户",required = true) String tenant,
            @WorkerParameter(value = "password",comment = "密码",required = true) String password)throws Exception{
        @Language("HQL") String validUser="from User where code=?1";
        List<User> users=dao.<List<User>, DefaultQuery>search(new DefaultQuery(validUser,List.of(user.getCode()))).getResult();
        Assert.isTrue(users.isEmpty(),"用户已被占用");
        user=dao.save(user).getResult();
        Account account=new Account();
        account.setAccount(user.getCode());
        account.setActived(true);
        account.setAccountTypes(getJsonMapper().writeValueAsString(userTypes));
        account.setTenant(tenant);
        account.setTenantId(tenant);
        accountManagerService.createAccount(account,password);
        return user;
    }
}
